import wx_sdk
import rtthread
from player import player
from recorder import recorder
import utime as time
from machine import Pin
from machine import LCD
from machine import RTC
import urequests as requests
import ujson as json


def main():
    print("Welcome to RT-Thread MicroPython!")
    LED = Pin(("LED",12),Pin.OUT_PP)
    LED.value(1)

    key_mid = Pin(("key_mid",13),Pin.IN,Pin.PULL_UP)
    key_up = Pin(("key_up",28),Pin.IN,Pin.PULL_UP)
    key_down = Pin(("key_down",19),Pin.IN,Pin.PULL_UP)
    key_right = Pin(("key_right",25),Pin.IN,Pin.PULL_UP)
    time.sleep_ms(100)
    key_mid.irq(trigger=Pin.IRQ_FALLING,handler=mid_func)
    key_up.irq(trigger=Pin.IRQ_FALLING,handler=up_func)
    key_down.irq(trigger=Pin.IRQ_FALLING,handler=down_func)
    key_right.irq(trigger=Pin.IRQ_FALLING,handler=right_func)
    #key_left = Pin(("key_left",24),Pin.IN,Pin.PULL_UP)
    #key_left.irq(trigger=Pin.IRQ_FALLING,handler=left_func)

    lcd = lcd_init()
    get_time()
    get_weather(lcd)
    time_update(lcd)

def lcd_init():                 # LCD初始化
    mlcd = LCD()
    mlcd.set_color(LCD.WHITE,LCD.BLACK)
    mlcd.fill(LCD.WHITE)
    mlcd.show_bmp(5, 238, "pictures/micropython.bmp")
    return mlcd

def lcd_show_time(lcd):              # 更新LCD显示
    #lcd.fill(LCD.GRAY)
    global alarm_hours
    global alarm_minutes
    global alarm_func
    global alarm_setting
    timestr = time.localtime()
    year = timestr[0]
    month = timestr[1]
    day = timestr[2]
    hrs = timestr[3]
    minute = timestr[4]
    sec = timestr[5]
    wday = timestr[6]
    #print("%d %d %d %d %d %d %d" %(year,month,day,hrs,minute,sec,wday))
    show_time = int_to_str(hrs)+":"+int_to_str(minute)+":"+int_to_str(sec)+" "
    show_day = int_to_str(year)+"/"+int_to_str(month)+"/"+int_to_str(day)
    lcd.text(show_day,35,10,32)
    lcd.text(show_time,50,75,32)
    if((hrs == alarm_hours)and(minute==alarm_minutes)and(alarm_func)):
        start_play(10)
        alarm_func = False

def lcd_show_alarm(lcd):
    operation = ["OFF","ON"]
    rectangle = [[45,75,85,105],[95,75,135,105],[140,75,200,105]]
    show_time = int_to_str(alarm_hours)+":"+int_to_str(alarm_minutes)+" "+operation[alarm_func]
    lcd.text(show_time,50,75,32)
    lcd.rectangle(rectangle[alarm_setting-1][0],rectangle[alarm_setting-1][1],rectangle[alarm_setting-1][2],rectangle[alarm_setting-1][3])

def time_update(mlcd):
    global alarm_setting
    while True:
        if(alarm_setting == 0):
            lcd_show_time(mlcd)
        else:
            lcd_show_alarm(mlcd)
        time.sleep(1)

def get_time():                                         # 获取网络时间
    head = {'User-Agent': 'Mozilla/5.0'}
    url = r'http://time1909.beijing-time.org/time.asp'
    response = requests.get(url=url,headers=head).text
    # 通过;分割文本；
    data = response.split(";")
    # ======================================================
    # 以下是数据文本处理：切割、取长度
    year = data[1][len("nyear") + 3: len(data[1])]
    month = data[2][len("nmonth") + 3: len(data[2])]
    day = data[3][len("nday") + 3: len(data[3])]
    wday = data[4][len("nwday")+3 : len(data[4])]
    hrs = data[5][len("nhrs") + 3: len(data[5])]
    minute = data[6][len("nmin") + 3: len(data[6])]
    sec = data[7][len("nsec") + 3: len(data[7])]
    timetup = (int(year), int(month), int(day), int(hrs), int(minute), int(sec),int(wday)-1,0)
    nowtime = (int(year), int(month), int(day), int(wday)-1,int(hrs), int(minute), int(sec),0)
    mytime = time.mktime(timetup)+946656000
    print(mytime)
    mrtc = RTC()                        # 初始化RTC模块     
    mrtc.init(nowtime)


def start_record(t):                             # 录音
    record = recorder()
    record.start("test.wav")
    time.sleep(t)
    record.stop()

def start_play(t):                              # 播放音频
    play = player()
    play.set_volume(80)
    play.opensong("http://music.163.com/song/media/outer/url?id=447925558.mp3")
    #play.opensong("test.wav")
    play.play()
    time.sleep(t)
    play.stop()

def network():
    #url = 'http://2211188im8.iask.in'
    url = 'https://aiapi.jd.com/jdai/asr'
    img = 'test.wav'                                # 上传图片的位置
    params = {                                      # 请求参数
        'Domain' : 'general',
        'Application-Id' : 'search-app',
        'Request-Id' : '56a847e6-84c0-4c01-bf4b-d566f2d2dd11',
        'Sequence-Id' : '-1',
        'Asr-Protocol' : '1',
        'Net-State' : '2',
        'Applicator' : '0',
        'Property' : '%7B%22autoend%22%3Afalse%2C%22encode%22%3A%7B%22channel%22%3A1%2C%22format%22%3A%22wav%22%2C%22sample_rate%22%3A16000%7D%2C%22platform%22%3A%22Linux%22%2C%22version%22%3A%220.0.0.1%22%7D',
        'appkey' : '2ca1e20761013f17f6c6721f59a47436',
        'secretkey' : '033c0318b7c64684e4f21625262ecc5f'
    }
    
    response = wx_sdk.wx_post_req( url, params, img=img )
    print( response.text ) 
    LED = Pin(("LED",12),Pin.OUT_PP)
    if '\u5f00\u706f' in response.text: # 开灯
        print("open lamp")
        LED.value(0) 
    if '\u5173\u706f' in response.text: # 关灯
        print("close lamp")
        LED.value(1)

def get_weather(mlcd):          # 请求本地天气
    cityid = "101091101"        # 城市编号
    url = "http://www.tianqiapi.com/api/?version=v6&cityid=" + cityid + "&appid=65251531&appsecret=Yl2bzCYb"

    r = requests.get(url)
    data = json.loads(r.content.decode())
    mlcd.text("Temp:%s-%s"%(data["tem2"], data["tem1"]), 10, 155, 32)   # 温度
    image = "pictures/" + data["wea_img"] + ".bmp"                      # 天气
    mlcd.show_bmp(190, 185, image)                                      # 显示天气图片


alarm_func = False
alarm_setting = 0
alarm_hours = 7
alarm_minutes = 0
    
def mid_func(v):                    # 中间按键按下中断
    global alarm_func
    if(alarm_func):
        alarm_func = False
    start_record(2)
    #start_play(5)
    network()
    

def up_func(v):
    global alarm_setting
    global alarm_hours
    global alarm_minutes
    global alarm_func
    print("up_func")
    if(alarm_setting == 1):
        alarm_hours += 1
        if(alarm_hours>23):
            alarm_hours = 0
    if(alarm_setting == 2):
        alarm_minutes += 1
        if(alarm_minutes>59):
            alarm_minutes = 0
    if(alarm_setting == 3):
        alarm_func = ~(alarm_func)
    print("%d %d %d" % (alarm_setting,alarm_hours,alarm_minutes))

def down_func(v):
    global alarm_setting
    global alarm_hours
    global alarm_minutes
    global alarm_func
    print("down_func")
    if(alarm_setting == 1):
        alarm_hours -= 1
        if(alarm_hours<0):
            alarm_hours =24
    if(alarm_setting == 2):
        alarm_minutes -= 1
        if(alarm_minutes<0):
            alarm_minutes = 60
    if(alarm_setting == 3):
        alarm_func = ~(alarm_func)
    print("%d %d %d" % (alarm_setting,alarm_hours,alarm_minutes))

def left_func(v):
    print("right_func")
    global alarm_setting
    alarm_setting -= 1
    if(alarm_setting<0):
        alarm_setting = 3
    print("%d %d %d" % (alarm_setting,alarm_hours,alarm_minutes))

def right_func(v):
    print("left_func")
    global alarm_setting
    alarm_setting += 1
    if(alarm_setting>3):
        alarm_setting = 0
    print("%d %d %d" % (alarm_setting,alarm_hours,alarm_minutes))


def int_to_str(num):                # 保持时间显示位数一致
    if num<10:
        return "0"+str(num)
    else : 
        return str(num)

    
if __name__ == '__main__':
    #start_record(5)
    rtthread.wifi_join("w0", "iqoo", "12345678")
    time.sleep(5)
    main()